//
//  TestQuestionView.swift
//  Auscultation
//
//  Created by zwb on 2021/3/30.
//

import UIKit

class HomePaddingLabel: UILabel {
    
    var textInsets: UIEdgeInsets = .zero
    
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: textInsets))
    }
    
    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insets = textInsets
        var rect = super.textRect(forBounds: bounds.inset(by: insets),
                                  limitedToNumberOfLines: numberOfLines)
        
        rect.origin.x -= insets.left
        rect.origin.y -= insets.top
        rect.size.width += (insets.left + insets.right)
        rect.size.height += (insets.top + insets.bottom)
        return rect
    }
    
}


class TestQuestionView: UIView {
    var normalColor = UIColor(hexString: "#F3F3F3")
    
    var seletedColor = UIColor(hexString: "#98f6c1")
    var okColor = UIColor(hexString: "#98f6c1")
    var errorColor = UIColor(hexString: "#fa5251")

    
    // 记录是否点击过答案
    var seltedAnswer = false
    
    var btns = [HomePaddingLabel]()
    var result : [String:Any] = [:]
    var examUserPaperQuestions:[Any] = []

    var complmentClouse:(([String:Any])->Void)?
    var seletedAnswerIndex = -1
    // 选中的答案 index 数组
    var seletedAnswerIndexArr = [Int]()

    var currentTime = 30
    var seletedIndex = 0{
        didSet{
            creatSubViews()
        }
    }
    var dataSource = [QuestionModel](){
        didSet{
            creatSubViews()
        }
    }
    var timer:DispatchSourceTimer?
    
    func creatSubViews() {
        for view in self.subviews {
            if view is UILabel {
                if view.lgf_Name == "answer" {
                    view.removeFromSuperview()
                }
            }
        }
        btns.removeAll()
        if seletedIndex >= dataSource.count {
            return
        }
        guard let answers = dataSource[seletedIndex].answerDic else { return  }
         let answerSort = dataSource[seletedIndex].answerSortArr
        questionL.text = dataSource[seletedIndex].content
        var i = 0
        
        for _ in answerSort {
            let btn = HomePaddingLabel()
            btns.append(btn)
            btn.textInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
            btn.lgf_Name = "answer"
            let key = answerSort[i]
            guard let value = answers[key] else { return  }
            let title = "\(key)" + "、" + "\(value)"
            btn.text = title
            btn.textColor = UIColor.init(lgf_HexString: "0F0F0F")
            btn.backgroundColor = normalColor
            btn.font = UIFont.systemFont(ofSize: 18)
            self.addSubview(btn)
            let top = 35 + i * 10 + i * 70
            btn.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.top.equalTo(questionL.snp.bottom).offset(top)
                make.height.greaterThanOrEqualTo(60)
            }
            btn.layer.cornerRadius = 5
            btn.layer.masksToBounds = true
            btn.numberOfLines = 0
            btn.lgf_AddTap(target: self, action: #selector(btnClick(tap:)))
            btn.tag = 10000 + i
            i = i + 1
        }
    }
    // MARK: - <#type#>
    lazy var progressView: GradientProgressView = {
        let progressView = GradientProgressView(frame: CGRect(x: 0, y: 0, width: UIDevice.lgf_ScreenW, height: 5))
        progressView.progressColors = [UIColor.init(lgf_HexString: "9CFFBF"), UIColor.init(lgf_HexString: "519BE7")]
        progressView.animationDuration = TimeInterval(currentTime)
        //动画时间函数
        progressView.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        return progressView
    }()
    
    // MARK: - <#type#>
    lazy var questionL: UILabel = {
        let questionL = UILabel()
        questionL.font = UIFont.boldSystemFont(ofSize: 18)
        questionL.textColor = UIColor.init(lgf_HexString: "0F0F0F")
        self.addSubview(questionL)
        questionL.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(48)
            make.right.equalTo(countDownView.snp.left).offset(-20)
        }
        questionL.numberOfLines = 0
        return questionL
    }()
    
    // MARK: - <#type#>
    lazy var countDownView: UIView = {
        let countDownView = UIView()
        countDownView.backgroundColor = UIColor.init(lgf_HexString: "F3F3F3")
        self.addSubview(countDownView)
        countDownView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-9)
            make.width.equalTo(75)
            make.height.equalTo(30)
            make.top.equalToSuperview().offset(15)
        }
        return countDownView
    }()
    
    // MARK: - <#type#>
    lazy var timeL: UILabel = {
        let timeL = UILabel()
        timeL.font = UIFont.boldSystemFont(ofSize: 18)
        timeL.textColor = UIColor.init(lgf_HexString: "A0A0A0")
        countDownView.addSubview(timeL)
        timeL.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(timeImage.snp.right).offset(9)
        }
        timeL.text = "\(self.currentTime)"
        timeL.numberOfLines = 0
        return timeL
    }()
    
    lazy var timeImage: UIImageView = {
        let timeImage = UIImageView()
        countDownView.addSubview(timeImage)
        timeImage.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(12)
            make.width.height.equalTo(16)
        }
        return timeImage
    }()

    lazy var nextBtn: UIButton = {
        let nextBtn = UIButton()
        self.addSubview(nextBtn)
        nextBtn.setTitleColor(.white, for: .normal)
        nextBtn.setBackgroundImage(UIImage(named: "矩形"), for: .normal)
        nextBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        nextBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(47)
            make.width.equalTo(250)
            make.bottom.equalToSuperview().offset(-UIDevice.lgf_TabBarH())
        }
        return nextBtn
    }()


    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(progressView)
        timeImage.image = UIImage(named: "shijian1")
        self.progressView.setProgress(0, animated: true)
        nextBtn.setTitle("下一题", for: .normal)
        self.countdown()
        result["examBeginTime"] = Date().lgf_TimeStampString()
        nextBtn.addTarget(self, action: #selector(TestQuestionView.nextBtnClick(btn:)), for: .touchUpInside)

    }
    
    @objc func nextBtnClick(btn:UIButton) {
        
        if seletedAnswerIndexArr.count <= 0 {
            SVProgressHUD.showMessage("请选择答案")
            return
        }
        
        nextPage(index: seletedAnswerIndex)

//        let questionModel = dataSource[seletedIndex]
//        let arr = questionModel.correctIndexArr!
//
//        // 选择正确
//        if seletedAnswerIndexArr == arr {
//            nextPage(index: seletedAnswerIndex)
//        }else{
//            for i in 0 ..< btns.count {
//                let btn = btns[i]
//                for index in arr {
//                    if i == index {
//                        btn.backgroundColor = okColor
//                    }
//                }
//                for seletedIndex in seletedAnswerIndexArr {
//                    if i == seletedIndex {
//                        btn.backgroundColor = errorColor
//                    }
//                }
//            }
//            // 正确答案
//            if seltedAnswer == false {
//                seltedAnswer = true
//            }else{
//                nextPage(index: seletedAnswerIndex)
//            }
//        }
    }
    
    func countdown()  {
      timer = dispatchTimer(timeInterval: 1, repeatCount: currentTime) { [weak self](timer, lastTime) in
            guard let self = self else { return }
        // 切换下一题
            if lastTime == 0{
                if self.seletedIndex >= self.dataSource.count - 1 {
                    print("完成")
                    self.result["examEndTime"] = Date().lgf_TimeStampString()
                    self.result["examUserPaperQuestions"] = self.examUserPaperQuestions
                    self.complmentClouse?(self.result)
                    return
                }
//                self.resetData()

            }else{
                self.timeL.text = "\(lastTime)"
                self.progressView.setProgress(Float(self.currentTime - lastTime / self.currentTime), animated: true)
            }
        }

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func btnClick(tap:UITapGestureRecognizer){
        guard let view = tap.view else { return  }
        let index = view.tag   - 10000
        seletedAnswerIndex = index
        let questionModel = dataSource[seletedIndex]
        if questionModel.type == "10" && seltedAnswer == false{
            for btn in btns {
                btn.backgroundColor = normalColor
            }
            view.backgroundColor = seletedColor
            seletedAnswerIndexArr.removeAll()
            seletedAnswerIndexArr.append(seletedAnswerIndex)
            
        }else if questionModel.type == "20" && seltedAnswer == false {
            view.backgroundColor = seletedColor
            // 多选的时候 防止重复先移除在添加
            seletedAnswerIndexArr.lgf_Remove(seletedAnswerIndex)
            seletedAnswerIndexArr.append(seletedAnswerIndex)
        }
        
                
        if seltedAnswer == true {
            return
        }
//        let questionModel = dataSource[seletedIndex]
        let arr = questionModel.correctIndexArr!
        
        // 选择正确
        if seletedAnswerIndexArr == arr {
//            nextPage(index: seletedAnswerIndex)
        }else{
            for i in 0 ..< btns.count {
                let btn = btns[i]
                for index in arr {
                    if i == index {
                        btn.backgroundColor = okColor
                    }
                }
                for seletedIndex in seletedAnswerIndexArr {
                    if i == seletedIndex {
                        btn.backgroundColor = errorColor
                    }
                }
            }
            // 正确答案
            if seltedAnswer == false {
                seltedAnswer = true
            }else{
//                nextPage(index: seletedAnswerIndex)
            }
        }

    }
    
    func nextPage(index:Int) {
        let question = dataSource[seletedIndex]
        let answerSort = question.answerSortArr
        guard let id = question.id else { return }
        let optionString = answerSort[index]
        let questionType = question.type
        var answersArr = [String]()
        answersArr.append(optionString)
        let answer = ["questionId":id.description,"answer":answersArr,"questionType":questionType] as [String : Any]
       
       self.examUserPaperQuestions.append(answer)
       print(index)
       
       if seletedIndex >= dataSource.count - 1 {
           print("完成")
           result["examEndTime"] = Date().lgf_TimeStampString()
           result["examUserPaperQuestions"] = examUserPaperQuestions
           complmentClouse?(result)
            timer?.cancel()
           return
       }
        
        resetData()
        if self.seltedAnswer == true {
            self.seltedAnswer = false
        }
    }
    
//     清空状态 进入下一题
    func resetData() {
        self.currentTime = 30
        seletedIndex = seletedIndex + 1
        self.progressView.progress = 0
        self.currentTime = 30
        self.timeL.text = "\(self.currentTime)"
        self.progressView.setProgress(0, animated: true)
        timer?.cancel()
        self.countdown()
        seletedAnswerIndex = -1
        seletedAnswerIndexArr.removeAll()
        seltedAnswer = false
    }
}

